<template>
  <div class="bdcToMoney hideScrollBar" ref="scrollEl">
    <div class="bdcToMoney-bg"></div>
    <!-- 导航 -->
    <NavBar
      isFixed
      :title="t('lotteryMoney.jjdh')"
      isTransparent
      :navScorllOffset="60"
      navScorllColor="#fff"
      :scrollEl="scrollEl"
      @getNavBarHeight="(h) => (pageData.navBarHeight = h)"
    />
    <!-- 内容 -->
    <div
      class="contentview"
      :style="{
        height: `calc(100vh - ${pageData.navBarHeight}px)`,
      }"
    >
      <!-- 头部 -->
      <div class="header items-center">
        <div class="header-text">{{ $t("lotteryMoney.kdjjed") }}</div>
        <div class="header-money">
          ${{
            toThousands(decimalToLength(pageData.availablePrizeDollarAmount))
          }}
        </div>
        <!-- <div class="header-desc">
          ${{ toThousands(decimalToLength(25151.0255)) }}奖金额度即将过期
        </div> -->
        <!-- 明细跳转 -->
        <img
          class="header-img"
          src="/image/lotterymoney/detail-icon.svg"
          @click="jumpPage('awardRedemption')"
        />
      </div>
      <!-- 兑换 -->
      <div class="exchange">
        <!-- 兑换输入框 -->
        <div class="inputbox">
          <div class="inputbox-title">
            {{ $t("lotteryMoney.qsrdjje") }}
          </div>
          <div class="inputbox-limit">
            <span>{{ $t("lotteryMoney.dbqdxz").split("xxx")[0] }}</span>
            <span style="color: #007bff">$5</span>
            <span>{{
              $t("lotteryMoney.dbqdxz").split("xxx")[1].split("---")[0]
            }}</span>
            <span style="color: #007bff">$500</span>
            <span>{{
              $t("lotteryMoney.dbqdxz").split("xxx")[1].split("---")[1]
            }}</span>
          </div>
          <!-- 输入框 -->
          <van-field
            class="inputbox-input"
            type="number"
            v-model="pageData.input"
            :maxlength="12"
            center
            :formatter="inputFormatter"
            label="$"
            label-width="10"
            label-class="inputbox-input-label"
            :placeholder="$t('airdrop.qsr')"
            @blur="handleBlur"
          >
            <template #button>
              <div class="inputbox-btn">
                ≈
                {{ toThousands(Number(pageData.input) * 1000) }} BDC
              </div>
            </template>
          </van-field>
          <div v-if="isBalancebdc" class="inputbox-error items-center">
            <img
              class="inputbox-error-icon"
              src="/image/lotterymoney/error-icon.svg"
            />
            {{ $t("lotteryMoney.kyyebz") }}
          </div>
          <div class="inputbox-desc">
            {{ $t("pledge.kyye") }}：{{
              toThousands(decimalToLength(Number(pageData.freeAmount)))
            }}
          </div>
          <!-- 兑换按钮 -->
          <div
            class="inputbox-exchange"
            :class="{
              'inputbox-exchange-activity': isExchange,
            }"
            @click="onExchange"
          >
            {{ t("lotteryMoney.qrdh") }}
          </div>
        </div>
        <!-- 介绍 -->
        <div class="rule">
          <div class="rule-desc items-center">
            <img class="rule-img" src="/image/assetDetails/desc-logo.svg" />
            {{ t("lotteryMoney.text1") }}
          </div>
          <div class="rule-desc items-center">
            <img class="rule-img" src="/image/assetDetails/desc-logo.svg" />
            {{ t("lotteryMoney.text2") }}
          </div>
          <div class="rule-desc items-center" @click="jumpPage('copy')">
            <img class="rule-img" src="/image/assetDetails/desc-logo.svg" />
            {{ t("lotteryMoney.text3") }}
          </div>
          <div class="rule-desc items-center">
            <img class="rule-img" src="/image/assetDetails/desc-logo.svg" />
            {{ t("lotteryMoney.text4") }}
          </div>
          <div class="rule-desc items-center" style="margin-bottom: 0px">
            <img class="rule-img" src="/image/assetDetails/desc-logo.svg" />
            {{ t("lotteryMoney.dyjpsdj") }}
          </div>
        </div>
      </div>
    </div>
    <!-- 兑奖弹窗 -->
    <ExchangePopup
      v-model:show="pageData.isShowPopup"
      :type="pageData.dhtype"
    ></ExchangePopup>
  </div>
</template>
<script setup name="exchangePoints">
import { toThousands, navigateI18nTo, decimalToLength } from "@/utils";
import {
  getWinerAvailablePrizeAmount,
  winnerPrizeExchange,
  getAccountInfo,
} from "@/api/lottery";
import { useGlobalStore } from "~~/store/global";
import { useThrottleFn } from "@vueuse/core";
import ExchangePopup from "../../components/lotterymoney/exchange-popup";
import * as MITO from "@zhj1214/qdjk-web";

const { t } = useI18n();
const scrollEl = ref();
const globalStore = useGlobalStore();

// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase

// 页面属性
const pageData = reactive({
  navBarHeight: 0,
  input: "",
  availablePrizeDollarAmount: 0, // 可兑奖额度 单位:美元
  freeAmount: 0, // BDC账户可用余额 单位:BDC
  isShowPopup: false,
  dhtype: 1,
});

// 可用余额是否不足
const isBalancebdc = computed(() => {
  if (Number(pageData.input) * 1000 > Number(pageData.freeAmount)) {
    return true;
  } else {
    return false;
  }
});

// 按钮是否可以兑奖
const isExchange = computed(() => {
  if (Number(pageData.availablePrizeDollarAmount) > 0) {
    if (pageData.input && Number(pageData.input) >= 5) {
      if (Number(pageData.input) <= 500) {
        if (Number(pageData.input) * 1000 <= Number(pageData.freeAmount)) {
          return true;
        }
      }
    }
  }

  return false;
});

// 输入校验
const inputFormatter = (value) => {
  // console.log("--", value);
  if (/^[0]/g.test(value) || /^[.]/g.test(value)) {
    return "";
  } else if (value.includes(".") && value.split(".")[1].length > 2) {
    value = decimalToLength(value);
  } else if (Number(value) > 500) {
    value = "500";
  } else if (Number(value) > Number(pageData.availablePrizeDollarAmount)) {
    return `${pageData.availablePrizeDollarAmount}`;
  }
  return value;
};

//  获取兑奖信息
const getWinerAvailablePrizeAmountRequest = () => {
  // zhjdebugger
  // pageData.availablePrizeDollarAmount = "19.69875";
  // pageData.freeAmount = "125.69875";
  //
  getWinerAvailablePrizeAmount().then((response) => {
    // console.log("--获取兑奖信息:", response);
    if (response) {
      pageData.availablePrizeDollarAmount = response.availablePrizeDollarAmount;
      pageData.freeAmount = response.freeAmount;
    }
  });
};

// 兑奖
const winnerPrizeExchangeRequest = () => {
  // 1. 使用 loading 遮罩
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
    zIndex: 999999999,
  });
  winnerPrizeExchange({
    exchangePrizeDollarAmount: pageData.input,
  }).then((res) => {
    // console.log("--res--", res);
    // closeToast();
    if (res != 1204 && res) {
      pageData.dhtype = 1;
      pageData.isShowPopup = true;
      pageData.input = "";
      getWinerAvailablePrizeAmountRequest();
    }
  });
};

// 避险账户,是否开通
const getAccountInfoRequest = async () => {
  const res = await getAccountInfo();
  console.log("--避险账户:", res);
  if (res) {
    // res.status 账户状态 0 未开通、1 已开通(正常账户)
    if (res.status == 1) {
      if (res.enabled) {
        pageData.dhtype = 1;
      } else {
        pageData.dhtype = 2;
      }
    } else {
      pageData.dhtype = 2;
    }
  } else {
    MITO.log({
      message: "避险账户信息,获取失败",
      tag: "手动上报",
      level: "low",
      ex: "手动上报",
    });
  }
};

onMounted(() => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_bdc_to_money_PUV");
  // 2. 获取兑奖信息
  getWinerAvailablePrizeAmountRequest();
  // 3. 避险账户
  getAccountInfoRequest();
});

// 兑奖
const onExchange = useThrottleFn(() => {
  if (!isExchange.value) return;
  if (pageData.dhtype != 1) {
    pageData.isShowPopup = true;
  } else {
    winnerPrizeExchangeRequest();
  }
}, 1000);

// 键盘收起时复原页面布局
const handleBlur = () => {
  window.scrollTo(0, 0);
};

// 点击-页面跳转
const jumpPage = async (val, isApp = false, params = null) => {
  if (isApp) {

  } else if (val === "awardRedemption") {
    firebase?.logEvent("BDC_H5_bdcToMoney_awardRedemption_Jump");
    navigateI18nTo({
      path: "/lottery-money/award-redemption",
    });
  } else if (val == "copy") {
    // navigateI18nTo({
    //   path: "/lottery-money/bdc-to-money-copy",
    // });
  }
};
</script>
<style lang="scss" scoped>
.header {
  position: relative;
  z-index: 9;
  justify-content: center;
  flex-direction: column;
  margin: 0 30px;
  height: 130 * 2px;
  border-radius: 12 * 2px 12 * 2px 0 0;
  background: linear-gradient(90deg, #007bff 0.34%, #00b2ff 100%);
  &-text {
    color: rgba(255, 255, 255, 0.7);
    font-size: 12 * 2px;
    margin-bottom: 12 * 2px;
  }
  &-money {
    color: #fff;
    font-size: 24 * 2px;
    font-weight: 700;
    margin-bottom: 3 * 2px;
  }
  &-desc {
    color: #ffd15a;
    font-size: 11 * 2px;
  }
  &-img {
    position: absolute;
    top: 12 * 2px;
    right: 16 * 2px;
    width: 28 * 2px;
    height: 28 * 2px;
    padding: 6 * 2px;
    border-radius: 6 * 2px;
    background: rgba(0, 40, 83, 0.1);
  }
}
.exchange {
  height: 100%;
  position: relative;
  z-index: 9;
  top: -10 * 2px;
  border-radius: 12 * 2px 12 * 2px 0 0;
  background: linear-gradient(
    180deg,
    rgba(255, 255, 255, 0.6) 0%,
    #f4f9fe 92.73%
  );
  border: 2px solid rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(15px);
}
.inputbox {
  margin: 20 * 2px 15 * 2px 0 * 2px 15 * 2px;
  padding: 20 * 2px 15 * 2px;
  border-radius: 24px;
  overflow: hidden;
  background-color: #fff;
  margin-bottom: 10 * 2px;
  &-title {
    color: #141924;
    font-size: 15 * 2px;
    font-weight: 590;
    margin-bottom: 7 * 2px;
    text-align: center;
  }
  &-limit {
    color: #999da7;
    font-size: 13 * 2px;
    margin-bottom: 24 * 2px;
    text-align: center;
  }
  &-input {
    font-size: 15 * 2px;
    font-weight: 600;
    color: #141924;
    background: rgba(115, 119, 128, 0.08);
    border-radius: 6 * 2px;
    height: 44 * 2px;
  }
  &-btn {
    font-size: 12 * 2px;
    color: #999da7;
    font-weight: 400;
  }
  &-error {
    margin-top: 6 * 2px;
    color: #ff4040;
    font-size: 11 * 2px;
    &-icon {
      width: 18 * 2px;
      height: 18 * 2px;
      margin-right: 5 * 2px;
    }
  }
  &-desc {
    margin-top: 15 * 2px;
    color: #141924;
    font-size: 12 * 2px;
  }
  &-exchange {
    margin-top: 25 * 2px;
    height: 96px;
    line-height: 96px;
    border-radius: 6 * 2px;
    text-align: center;
    background-color: #a0ceff;
    color: #fff;
    font-size: 30px;
    font-weight: 590;
    margin-bottom: 30px;
    &-activity {
      background-color: #007bff;
    }
  }
}
.bdcToMoney {
  background-color: #f4f5f7;
  min-height: 100vh;
  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 300 * 2px;
    background: linear-gradient(
      180deg,
      #96c9ff 0%,
      rgba(236, 245, 255, 0) 100%
    );
  }
}
.rule {
  margin: 0 15 * 2px;
  background-color: #fff;
  padding: 20 * 2px 15 * 2px;
  border-radius: 12 * 2px;
  overflow: hidden;
  &-img {
    width: 11 * 2px;
    height: 11 * 2px;
    margin-top: 2 * 2px;
    margin-right: 8 * 2px;
  }
  &-desc {
    align-items: flex-start;
    font-size: 12 * 2px;
    color: #999da7;
    line-height: 16 * 2px;
    margin-bottom: 15 * 2px;
  }
}
</style>
<style>
.inputbox-input-label {
  font-size: 15 * 2px;
  color: #999da7 !important;
  font-weight: 600;
}
</style>
